/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bizfty.apimanager;

import com.bizfty.api.apimanager.gateways.ApiMgmt;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import javax.xml.ws.Endpoint;
import org.apache.cxf.Bus;
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 *
 * @author johns
 */
@Configuration
public class CxfConfig {

    @Autowired
    private Bus bus;
    
    @Bean
    @Qualifier("apiMgmt") // 注入webService  
    public Endpoint weixinEndpoint(ApiMgmt apiMgmt) throws IOException {
        EndpointImpl endpoint = new EndpointImpl(bus, apiMgmt);
        //endpoint.setWsdlLocation(getSchemaPath("/wsdl/WeixinService.wsdl"));
//        String[] paths = {"/schema/schema1.xsd","/schema/schema2.xsd","/schema/schema3.xsd","/schema/schema4.xsd"};
//        endpoint.setSchemaLocations(getSchemaPath(paths));
        endpoint.publish("/ApiMgmt");
        return endpoint;
    }
    
    @Bean
    @Qualifier("apiMgmt") // 注入webService
    public Server rsServer(ApiMgmt apiMgmt) throws IOException {
        JAXRSServerFactoryBean endpoint = new JAXRSServerFactoryBean();
        endpoint.setBus(bus);
        endpoint.setAddress("/apiResource");
//        endpoint.setDocLocation(getSchemaPath("/wadl/WeixinService.wadl"));
        endpoint.setServiceBeans(Arrays.<Object>asList(apiMgmt));
//        String[] paths = {"/schema/schema1.xsd","/schema/schema2.xsd","/schema/schema3.xsd","/schema/schema4.xsd"};
//        endpoint.setSchemaLocations(getSchemaPath(paths));
        return endpoint.create();
    }
    private String getSchemaPath(String path) throws IOException{
        Enumeration<URL> urls;
        urls= this.getClass().getClassLoader().getResources(path);
        return urls.nextElement().getPath();
    }
    private List<String> getSchemaPath(String[] paths) throws IOException{
        Enumeration<URL> urls;
        List<String> schemas = new ArrayList<String>();
        for(String path : paths){
            urls= this.getClass().getClassLoader().getResources(path);
            schemas.add(urls.nextElement().getPath());
        }
        return schemas;
    }
}
